//
//  CLLUserAccount.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/12.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import YYModel
// 用户保存文件名
let useraccount:String = "userAccount.json"
/// 用户信息模型
class CLLUserAccount: NSObject {

    /// accesstoken
    var access_token:String?
    /// uid
    var uid: String?
    /// 过期时间
    var expires_in:TimeInterval = 0{
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate:Date?
    /// 用户昵称
    var screen_name:String?
    /// 用户图片
    var avatar_large:String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    // 程序启动  加载沙盒中的数据
    override init() {
        super.init()
        // 获取沙盒路径
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(useraccount)
        // 取出数据
        guard let data = NSData(contentsOfFile: filePath) ,
            // 数据反序列化
            let dict = try? JSONSerialization.jsonObject(with: (data as Data), options: []) as? [String:Any]
        else {
            return
        }
        // 最为关键的一步--为登录信息赋值:赋值成功，切换授权/登录界面
        yy_modelSet(with: dict!)
        
        // 处理过期时间
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            access_token = nil
            uid = nil
            // 移除沙盒文件
            try? FileManager.default.removeItem(atPath: filePath)
            print("token过期,请授权")
        }
        
    }
}

extension CLLUserAccount {
    func saveAccount(){
        // 模型转字典
        var dict = self.yy_modelToJSONObject() as? [String:Any]
        // 需要删除expires_in字段的值
        dict?.removeValue(forKey: "expires_in")
        // 将字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict ?? [:], options: []) else {
            return
        }
        // 将序列化的数据存入沙盒
        // 路径
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = (docPath as NSString).appendingPathComponent(useraccount)
        // 保存
        (data as NSData).write(toFile: filePath, atomically: true)
        print("用户信息保存成功\(filePath)")
        
    }
}

